package com.example.springgateway.config;

import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
import io.github.resilience4j.timelimiter.TimeLimiterConfig;
import org.springframework.cloud.circuitbreaker.resilience4j.ReactiveResilience4JCircuitBreakerFactory;
import org.springframework.cloud.circuitbreaker.resilience4j.Resilience4JConfigBuilder;
import org.springframework.cloud.client.circuitbreaker.Customizer;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @createBy guoqiang
 * @createTime 2019/4/4
 * @describe
 */
@Configuration
public class Config {
//    public static void main(String[] args) {
////        int length=10;
////        boolean isSpeStr=true;
////        String str=genRandomStr(length,isSpeStr);
////        System.out.println(str);
//    }

    private static String genRandomStr(int length, boolean isSpeStr) {
        String str = "abcdefghih";
        String speStr = "_+-&=!@#$%^";
        List<Integer> indexs = new ArrayList<Integer>();
        for (int i = 0; i < length; i++) {
            Random random = new Random();
            int randomInt = random.nextInt(10);
            indexs.add(randomInt);
        }
        StringBuilder stb = new StringBuilder();
        if (isSpeStr) {
            for (int i = 0; i < str.length() / 2; i++) {
                stb.append(str.charAt(indexs.get(i)));
                stb.append(speStr.charAt(indexs.get(i)));
            }
        } else {
            for (int i = 0; i < str.length(); i++) {
                stb.append(str.charAt(indexs.get(i)));
            }
        }
        return stb.reverse().toString();
    }

    /**
     * 限流解析器，与requestRateLimter 配合使用
     */
    @Bean
    KeyResolver apiKeyResolver() {
        //按照url限流
        return exchange -> Mono.just(exchange.getRequest().getPath().toString());
    }

    /**
     * 与断路器配合使用
     * @return
     */
    @Bean
    public Customizer<ReactiveResilience4JCircuitBreakerFactory> defaultCustomizer() {
        return factory -> factory.configureDefault(id -> new Resilience4JConfigBuilder(id)
                .circuitBreakerConfig(CircuitBreakerConfig.ofDefaults())
                .timeLimiterConfig(TimeLimiterConfig.custom().timeoutDuration(Duration.ofMillis(5000)).build())
                .build());
    }


}
